package com.googlecode.monitoring.service;

import com.googlecode.monitoring.dao.AgentConfigurationDao;
import com.googlecode.monitoring.model.AlertText;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Service(value = "alertTextService")
public class AlertTextService {
    private AgentConfigurationDao agentConfigurationDao;

    @Autowired
    public void setAgentConfigurationDao(AgentConfigurationDao agentConfigurationDao) {
        this.agentConfigurationDao = agentConfigurationDao;
    }

    public SimpleMailMessage buildMessage(Person person, ItemToCheck item) {
        Map<String, Object> context = new HashMap<String, Object>();
        context.put("person", person);
        context.put("item", item);

        AlertText alertText = agentConfigurationDao.getAlertText();
        SimpleMailMessage message = new SimpleMailMessage();
        StringBuilder text = new StringBuilder();
        try {
            text.append(agentConfigurationDao.replacePlaseHoldersInAlertText(context, alertText.getHeader()));
            text.append("\n\n");
            text.append(agentConfigurationDao.replacePlaseHoldersInAlertText(context, alertText.getMain()));
            text.append("\n\n");
            text.append(agentConfigurationDao.replacePlaseHoldersInAlertText(context, alertText.getFooter()));
            text.append("\n\n");
            message.setText(text.toString());
            message.setSubject(agentConfigurationDao.replacePlaseHoldersInAlertText(context, alertText.getSubject()));
            message.setTo(person.getEmail());
            message.setFrom("monitoring@gmail.com");
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();  
        }
        return message;
    }
}
